﻿using BenCaoXuan.Infrastructure.Attr;
using BenCaoXuan.Infrastructure.Dto;
using BenCaoXuan.Infrastructure.Dto.Admin.employee;
using BenCaoXuan.Infrastructure.EFCore.MySql;
using BenCaoXuan.Infrastructure.IOC;
using BenCaoXuan.Infrastructure.Redis;
using BenCaoXuan.Infrastructure.Tools;
using BenCaoXuan.Service.Interface.admin;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;
using System.Configuration;
using System.Security.Principal;

namespace BenCaoXuan.Service.Instance.admin
{
    [Inject_]
    public class Login_Service :Base_Service, I_Login_Service
    {
        private readonly Login_IOC _login_IOC;
        private readonly RedisStringService _redisStringService;
        private readonly IConfiguration _configuration;
        private readonly RedisHashService _redisHashService;

        public Login_Service(
            RedisHashService redisHashService,
            Login_IOC login_IOC,
            RedisStringService redisStringService,
            IConfiguration configuration)
        {
            _login_IOC = login_IOC;
            _redisStringService = redisStringService;
            _configuration = configuration;
            _redisHashService = redisHashService;
        }

        /// <summary>
        /// 检查登录
        /// </summary>
        /// <param name="v1"></param>
        /// <param name="v2"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public Employee_Dto? Check_Login(string code, string account)
        {
            var redis = _configuration["Redis:Keys:Check_Login"];
            var _employee= _redisHashService.GetValueFromHash(redis + account, code!);//获取员工信息

            if (!string.IsNullOrEmpty(_employee))//获取到了代表当前code是有效的
            {
                return JsonConvert.DeserializeObject<Employee_Dto>(_employee)!;
                //直接把信息返回回去即可
            }
            else
                return null;
        }

        /// <summary>
        /// 初始化员工密码
        /// </summary>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Api_Result_Dto> Init_User()
        {
            var employee = await _login_IOC._sysEmployee_EFCore.GetAll().ToListAsync();
            employee.ForEach(d =>
            {
                var salt = Config.GUID2();
                d.ESalt = salt;
                d.EPassword = EncryptUtil.LoginMd5("0921", salt);
            });

            _login_IOC._sysEmployee_EFCore.UpdateRange(employee);
            _login_IOC._sysEmployee_EFCore.SaveChanges();

            return Get_Result(0);

        }
        
        /// <summary>
        /// 员工登录
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public  async Task<Api_Result_Dto> Logins(Login_Dto dto)
        {
            var iq = _login_IOC._sysEmployee_EFCore.GetAll(d => d.EAccount == dto.account);
            if (!await iq.AnyAsync())
            {
                return Get_Result(-1, "账号或者密码错误");
            }

            var employee = await iq.SingleAsync();
            var pwd = EncryptUtil.LoginMd5(dto.password!, employee.ESalt!);
            if (employee.EPassword != pwd)
            {
                return Get_Result(-1, "账号或者密码错误");
            }

            if (employee.EIsBan == 1)
            {
                return Get_Result(-1, "账号已被禁用");
            }

            //添加登录日志
            var result = AddLog(new SysLoginLog()
            {
                LlId = Config.GUID2(),
                LlEid = employee.EId,
                LlCode = dto.code,
                LlEname = employee.EName!,
                LlIpaddress = Config.GetIp(),
                LlLoginTime = DateTime.Now,
                LlRemark = employee.ERemark,
            });
            if (result > 0) {
                //保存code到redis
                var jwt = _configuration["Redis:Keys:Check_Login"];
                var data = new
               Employee_Dto
                {
                    id = employee.EId,
                    account = employee.EAccount,
                    name = employee.EName,
                    photo = employee.EPhoto,
                };

                _redisHashService.RemoveEntry(jwt + dto.account!);//移除哈希中所有数据
                //下一次登录时,将用户之前的code清空
                _redisHashService.SetEntryInHash(jwt + dto.account!, dto.code!, JsonConvert.SerializeObject(data));
            }

            
            
           


            return Get_Result(0,"登陆成功");

        }

        private int AddLog(SysLoginLog log)
        {
            _login_IOC._sysLoginLog_EFCore.Add(log);

            return _login_IOC._sysLoginLog_EFCore.SaveChanges();
        }

    }
}
